package JaggSoft;

import JaggSoft.Utilidades.*;
import java.awt.event.KeyEvent;
import javax.swing.*;

public class Principal extends javax.swing.JFrame {
    private enum Tipo{ADMINISTRADOR,USUARIO,NINGUNO};
    private Tipo permiso;
    public Principal() {
        initComponents();
        jlMensaje.setText("");
        this.setVisible(false);
        this.setLocationRelativeTo(null);
        jdLogin.setSize(280,165);
        jdLogin.setLocationRelativeTo(this);
        jdLogin.show();
    }
    private void SetDatosBoton(JButton boton,String nombre_boton,int x,int y,int ancho,int alto){
        boton.setToolTipText(nombre_boton);
        boton.setBounds(x,y,ancho,alto);
        jpMenu.add(boton);
    }
    private void EstablecerPermisos(){
        if(permiso==Tipo.ADMINISTRADOR){
            JButton jbBodega=new JButton(new ImageIcon(getClass().getResource("/Recursos/bodega.png")));
            JButton jbUsuarios=new JButton(new ImageIcon(getClass().getResource("/Recursos/usuarios.png")));
            //JButton jbBitacora=new JButton(new ImageIcon(getClass().getResource("/Recursos/bitacora.png")));
            JButton jbProducto=new JButton(new ImageIcon(getClass().getResource("/Recursos/producto.png")));
            //JButton jbReportes=new JButton(new ImageIcon(getClass().getResource("/Recursos/reporte.png")));
            
            SetDatosBoton(jbBodega,"Bodega",6,6,48,48);
            SetDatosBoton(jbUsuarios,"Usuarios",6,60,48,48);
            SetDatosBoton(jbProducto,"Productos",6,114,48,48);
            /*SetDatosBoton(jbReportes,"Reportes",6,168,48,48);
            SetDatosBoton(jbBitacora,"Bitacora",6,222,48,48);*/
            
            jbBodega.addActionListener(new ManejadorEventoClick(this.desktopPane,"JaggSoft.Bodegas"));
            jbUsuarios.addActionListener(new ManejadorEventoClick(this.desktopPane,"JaggSoft.Usuarios"));
            //jbBitacora.addActionListener(new ManejadorEventoClick(this.desktopPane,"JaggSoft.Bitacora"));
            jbProducto.addActionListener(new ManejadorEventoClick(this.desktopPane,"JaggSoft.Productos"));
            //jbReportes.addActionListener(new ManejadorEventoClick(this.desktopPane,"JaggSoft.Reportes"));
        }
        else{
            JButton jbSolicitud=new JButton(new ImageIcon(getClass().getResource("/Recursos/solicitud.png")));
            JButton jbDevolucion=new JButton(new ImageIcon(getClass().getResource("/Recursos/devolucion.png")));
            JButton jbIngreso=new JButton(new ImageIcon(getClass().getResource("/Recursos/ingresos.png")));
            JButton jbSolicitante=new JButton(new ImageIcon(getClass().getResource("/Recursos/ingresos.png")));
            
            SetDatosBoton(jbSolicitud,"Solicitudes",6,6,48,48);
            SetDatosBoton(jbDevolucion,"Devoluciones",6,60,48,48);
            SetDatosBoton(jbIngreso,"Ingreso y Distribución de Producto",6,114,48,48);
            SetDatosBoton(jbSolicitante,"Solicitantes",6,168,48,48);
            
            jbDevolucion.addActionListener(new ManejadorEventoClick(this.desktopPane,"JaggSoft.Devoluciones"));
            jbSolicitante.addActionListener(new ManejadorEventoClick(this.desktopPane,"JaggSoft.Solicitud"));
        }
    }
    private Tipo ValidarPermisos(){
        String columnas[]={"Tipo","Descripcion"};
        JTable tabla=Conexion.ObtenerTabla("SELECT id_usuario,id_tipo FROM usuario WHERE usuario='"+jtfUsuario.getText()+"' AND pass='"+jtfPassword.getText()+"'",columnas);
        if(tabla.getRowCount()>0){
            if(tabla.getValueAt(0,1).toString().equals("1"))
                return Tipo.ADMINISTRADOR;
            return Tipo.USUARIO;
        }
        return Tipo.NINGUNO;
    }
    private boolean ValidarCampos(){
        if(jtfUsuario.getText().length()==0)
            jlMensaje.setText("Debe ingresar el usuario"+(jtfPassword.getText().length()>0?".":" y contraseña."));
        else{
            if(jtfPassword.getText().length()==0)
                jlMensaje.setText("Debe ingresar la constraseña.");
            else
                return true;
        }
        return false;
    }
    private void SoloAlfanumericos(KeyEvent evt){
        char tecla=evt.getKeyChar();
        if((tecla<'a'||tecla>'z')&&(tecla<'A'||tecla>'Z')&&(tecla<'0'||tecla>'9')&&(tecla!=8)&&(tecla!=35)&&(tecla!=36)&&(tecla!=127)&&(evt.getKeyChar()!='ñ')&&(evt.getKeyChar()!='Ñ')){
            evt.consume();
            jlMensaje.setText("Solo se permiten caracter alfanuméricos.");
        }
        else
            jlMensaje.setText("");
    }
    private void Login(){
        if(ValidarCampos()){
            permiso=ValidarPermisos();
            if(permiso==Tipo.NINGUNO)
                jlMensaje.setText("El usuario no existe.");
            else{
                EstablecerPermisos();
                this.setVisible(true);
                jdLogin.setVisible(false);
                jdLogin=null;
            }
        }
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jdLogin = new javax.swing.JDialog();
        jtfUsuario = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        btnLogin = new javax.swing.JButton();
        jtfPassword = new javax.swing.JPasswordField();
        jlMensaje = new javax.swing.JLabel();
        desktopPane = new javax.swing.JDesktopPane();
        jpMenu = new javax.swing.JPanel();

        jdLogin.setTitle("Inicio de Sesión");
        jdLogin.setIconImage(new ImageIcon(getClass().getResource("/Recursos/icono.png")).getImage());
        jdLogin.addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                jdLoginWindowClosing(evt);
            }
        });

        jtfUsuario.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jtfUsuarioKeyTyped(evt);
            }
        });

        jLabel2.setText("Usuario:");

        jLabel3.setText("Contraeña:");

        btnLogin.setText("Ingresar");
        btnLogin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLoginActionPerformed(evt);
            }
        });

        jtfPassword.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jtfPasswordKeyTyped(evt);
            }
        });

        jlMensaje.setForeground(new java.awt.Color(255, 0, 0));
        jlMensaje.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jlMensaje.setText("mensaje");

        javax.swing.GroupLayout jdLoginLayout = new javax.swing.GroupLayout(jdLogin.getContentPane());
        jdLogin.getContentPane().setLayout(jdLoginLayout);
        jdLoginLayout.setHorizontalGroup(
            jdLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jdLoginLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jdLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jdLoginLayout.createSequentialGroup()
                        .addGroup(jdLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jdLoginLayout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jtfPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jdLoginLayout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addGap(18, 18, 18)
                                .addComponent(jtfUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jlMensaje, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
            .addGroup(jdLoginLayout.createSequentialGroup()
                .addGap(89, 89, 89)
                .addComponent(btnLogin)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jdLoginLayout.setVerticalGroup(
            jdLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jdLoginLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jdLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jtfUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jdLoginLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jtfPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jlMensaje)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnLogin)
                .addContainerGap())
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("StockManager");
        setIconImage(new ImageIcon(getClass().getResource("/Recursos/icono.png")).getImage());
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });

        javax.swing.GroupLayout jpMenuLayout = new javax.swing.GroupLayout(jpMenu);
        jpMenu.setLayout(jpMenuLayout);
        jpMenuLayout.setHorizontalGroup(
            jpMenuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 70, Short.MAX_VALUE)
        );
        jpMenuLayout.setVerticalGroup(
            jpMenuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 600, Short.MAX_VALUE)
        );

        jpMenu.setBounds(0, 0, 70, 600);
        desktopPane.add(jpMenu, javax.swing.JLayeredPane.DEFAULT_LAYER);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(desktopPane, javax.swing.GroupLayout.DEFAULT_SIZE, 1000, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(desktopPane, javax.swing.GroupLayout.DEFAULT_SIZE, 650, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoginActionPerformed
        Login();
    }//GEN-LAST:event_btnLoginActionPerformed
    private void jdLoginWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_jdLoginWindowClosing
        System.exit(0);
    }//GEN-LAST:event_jdLoginWindowClosing
    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
        jpMenu.setBounds(jpMenu.getX(),jpMenu.getY(),jpMenu.getWidth(),this.getHeight());
    }//GEN-LAST:event_formComponentResized
    private void jtfUsuarioKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfUsuarioKeyTyped
        SoloAlfanumericos(evt);
    }//GEN-LAST:event_jtfUsuarioKeyTyped
    private void jtfPasswordKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfPasswordKeyTyped
        SoloAlfanumericos(evt);
    }//GEN-LAST:event_jtfPasswordKeyTyped
    public static void main(String args[]) {
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
           for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Principal();
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnLogin;
    private javax.swing.JDesktopPane desktopPane;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JDialog jdLogin;
    private javax.swing.JLabel jlMensaje;
    private javax.swing.JPanel jpMenu;
    private javax.swing.JPasswordField jtfPassword;
    private javax.swing.JTextField jtfUsuario;
    // End of variables declaration//GEN-END:variables
}